import 'dart:convert';

import 'package:connectivity/connectivity.dart';
import 'package:dio/dio.dart';
import 'package:flutter_example/http/http_manager.dart';

class ResponseInterceptor extends InterceptorsWrapper {
  @override
  Future onRequest(RequestOptions options) async {
    /// 检查网络是否连接
    ConnectivityResult result = await (Connectivity().checkConnectivity());

    if (result == ConnectivityResult.none) {
      DioError error = ResponseInterError().transform(options: options);
      return Future.error(error);
    }

    return super.onRequest(options);
  }

  @override
  Future onResponse(Response response) {
    try {
      Map<String, dynamic> responseData = jsonDecode(response.data);
      String code = responseData["code"].toString();

      // 业务-接口错误编码
      if (code == "-1") {
        String message = responseData["message"].toString();
        DioError error = ResponseInterError(code: code, message: message)
            .transform(response: response);
        return Future.error(error);
      }

      // 业务-未登录编码
      if (code == "0000001" || code == "0000002") {
        ResponseInterError error =
            ResponseInterError(code: code, message: "用户未登录");
        HttpManager().cancelAll(error: error);
      }
    } catch (e, s) {
      print("响应解析过程逻辑错误：$e\n\n$s");
      DioError error = ResponseInterError(message: e.toString())
          .transform(response: response);
      return Future.error(error);
    }
    return super.onResponse(response);
  }

  @override
  Future onError(DioError err) {
    print("onError!");
    DioError error;
    if (!(err.error is ResponseInterError)) {
      error = ResponseInterError().transform(error: err);
    }
    return super.onError(error);
  }
}

/// 响应报错
class ResponseInterError {
  static const String DEFAULT_ERROR_MESSAGE = "网络异常，请稍后重试！";
  static const String DEFAULT_ERROR_CODE = "-1";

  String code;
  String message;

  ResponseInterError({
    this.code = DEFAULT_ERROR_CODE,
    this.message = DEFAULT_ERROR_MESSAGE,
  });

  DioError transform({
    DioError error,
    RequestOptions options,
    DioErrorType type = DioErrorType.DEFAULT,
    Response response,
  }) {
    // 生成默认 `DioError` 对象
    DioError dioError = DioError(
      error: this,
      request: options,
      response: response,
      type: type,
    );

    if (error != null) {
      dioError = error;

      //this.code = "-1";
      //this.message = error.message;

      switch (error.type) {
        case DioErrorType.CONNECT_TIMEOUT:
          this.message = "网络连接超时，请检查网络设置";
          break;
        case DioErrorType.RECEIVE_TIMEOUT:
          this.message = "服务器异常，请稍后重试！";
          break;
        case DioErrorType.SEND_TIMEOUT:
          this.message = "网络连接超时，请检查网络设置";
          break;
        case DioErrorType.RESPONSE:
          {
            try {
              int statusCode = error.response.statusCode;
              String statusMessage = error.response.statusMessage;

              switch (statusCode) {
                case 400:
                  this.message = "服务器异常，请稍后重试！";
                  break;
                default:
                  this.message = statusMessage;
              }
            } catch (e) {
              this.message = "服务器异常，请稍后重试！";
            }
          }
          break;
        case DioErrorType.CANCEL:
          this.message = "请求已被取消，请重新请求";
          break;
        case DioErrorType.DEFAULT:
          this.message = "网络异常，请稍后重试！";
          break;
      }

      dioError.error = this;
    }

    return dioError;
  }
}
